#!/usr/bin/env python

import os
import urllib2
import sqlalchemy as sa

from datetime import datetime
from model import DeclarativeBase
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers


__all__ = ['Document']

class Document(DeclarativeBase):
    '''Document class
    
    @author Julot <andy.julot@gmail.com>
    @since Tuesday, April 17, 2012. 05:02 PM'''
    
    __tablename__ = 'documents'
        
    id = sa.Column(sa.Integer, primary_key=True)
    code = sa.Column(sa.String, nullable=False, index=True)
    extension = sa.Column(sa.String(4), nullable=False, index=True)
    synopsis = sa.Column(sa.Text, nullable=False)
    files = sa.Column(sa.Text, nullable=False)
    createdAt = sa.Column(sa.DateTime, default=datetime.now)
    updatedAt = sa.Column(sa.DateTime, default=datetime.now,
                          onupdate=datetime.now)
    
    def upload(self, fileLocation):
        url = 'http://localhost/Aya/Miyabi/api/document'
        #url = 'http://apl.pojokdomain.com/miyabi/api/document'
        
        register_openers()
        
        path = os.path.join(fileLocation, self.files)
        fileObject = open(path, 'rb')
        params = {'Document[file]': fileObject, 'code': self.code,
                  'synopsis': self.synopsis}
        datagen, headers = multipart_encode(params)
        request = urllib2.Request(url, datagen, headers)
        request.add_header('X_REST_USERNAME', 'rest-user@miyabi')
        request.add_header('X_REST_PASSWORD', 'MiyabiRestUser')
        
        try:
            return urllib2.urlopen(request).read()
        except:
            return None
    
    def download(self, type='pdf'):
        url = 'http://localhost/Aya/Miyabi/document/download/%s'
        #url = 'http://apl.pojokdomain.com/miyabi/document/download/%s'
        request = urllib2.Request(url % self.id)
        request.add_header('X_REST_USERNAME', 'rest-user@miyabi')
        request.add_header('X_REST_PASSWORD', 'MiyabiRestUser')
        path = os.path.join('document', '%s.pdf' % self.id)
        file = open(path, 'wb')
        r = self._download(request, file=file)
        file.close()
        return path if r else None
    
    def _download(self, request, reportHook=None, file=None):
        try:
            r = urllib2.urlopen(request)
            meta = r.info()
            self.size = -1
            if meta.has_key('Content-Length'):
                try: self.size = long(meta.getheader('Content-Length'))
                except: pass
            progress = 0
            result = ''
            count = 0
            block = 1024
            if self.size != -1:
                if reportHook: reportHook(count, block, self.size)
            for chunk in iter(lambda: r.read(block), ''):
                count += 1
                if file: file.write(chunk)
                else: result += chunk
                if reportHook: reportHook(count, block, self.size)
        except:
            return False
        return True if file else result
